'use strict'

const _ = require('lodash')
const moment = require('moment')
const Env = use('Env')
const { AliYunService } = require('../../Services')
const { DriveRecord, SmsCheck } = require("../../Models");
class DriveController {
  async index({ request, response, params }) {
    const { name, mobile, page, pageSize = 999 } = request.all()
    let query = DriveRecord.query()
    if (name) {
      query = query.whereRaw('name like ?', [`%${name}%`])
    }
    if (mobile) {
      query = query.whereRaw('mobile like ?', [`%${mobile}%`])
    }
    query = await query
      .orderBy('createdAt', 'desc')
      .paginate(page, pageSize)
    response.json(query)
  }
  /* 发送code */
  async code({ request, response }) {
    const { mobile } = request.all()
    const mobileReg = new RegExp(/^1[0-9]{10}$/)
    if (!mobileReg.test(mobile)) {
      throw { error: 1012, message: '手机号码错误' }
    }
    const code = Math.floor(Math.random() * (9999 - 1000)) + 1000
    await AliYunService.sendSMS(
      mobile,
      'SMS_165415774',
      {
        code: code
      }
    )
    const record = await SmsCheck.findBy('mobile', mobile)
    if (!record) {
      await SmsCheck.create({
        code: code,
        isChecked: 1,
        mobile: mobile,
        expiredAt: moment().add(5, 'm').toDate()
      })
    } else {
      record.code = code
      record.isChecked = 1
      record.expiredAt = moment().add(5, 'm').toDate()
      await record.save()
    }
    response.json({
      code: 0,
      message: 'success'
    })
  }

  async create({ request, response }) {
    const { name, mobile, code, province, city, driveType, district } = request.all()
    console.log('request.all(): ', request.all());
    if (!name || !mobile || !code || !province || !city || !driveType || !district) {
      throw { error: 1012, message: '参数错误' }
    }
    const smsCheck = await SmsCheck.findBy('mobile', mobile)
    if (!smsCheck) {
      throw { error: 1012, message: '验证码错误' }
    }
    if (moment().isAfter(smsCheck.expiredAt) || code != smsCheck.code || smsCheck.isChecked == 2) {
      throw { error: 1012, message: '验证码错误' }
    }
    await DriveRecord.create({
      name: name,
      mobile: mobile,
      province: province,
      city: city,
      district: district,
      driveType: driveType === 1 ? 'ER6' : 'MARVEL R'
    })
    smsCheck.isChecked = 2
    await smsCheck.save()
    response.json({
      code: 0,
      msg: 'success'
    })
  }
}

module.exports = DriveController
